package org.atlantis.grosbeak.lang.inject;

import java.lang.reflect.Method;

import org.atlantis.grosbeak.castor.Castors;
import org.atlantis.grosbeak.lang.Exceptions;

/**
 * 通过Setter方法给字段注入值。
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">SeeNoEvil</a>
 * 
 */
public class SetterInjector implements Injecting {

	private Method setter;
	private Class<?> paramType;

	public SetterInjector(Method setter) {
		this.setter = setter;
		paramType = setter.getParameterTypes()[0];
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.atlantis.grosbeak.lang.inject.Injecting#inject(java.lang.Object,
	 * java.lang.Object)
	 */
	public void inject(Object target, Object value)
			throws FailToInjectException {
		Object val = null;
		try {
			val = Castors.me().castTo(value, paramType);
			setter.invoke(target, val);
		} catch (Exception e) {
			throw Exceptions.makeThrow(FailToInjectException.class,
					"Fail to set '%s' by setter '%s.%s()', because [%s].",
					value, setter.getDeclaringClass().getName(), setter
							.getName(), e.getMessage());
		}
	}
}
